/*
 * Copyright @2011 Dnbiz. All rights reserved.
 */
package com.dnbiz.api.sdk.util;

import java.lang.reflect.Field;

import com.dnbiz.api.sdk.ApiParameter;

/**
 * <pre>
 * API参数组装工具类
 * </pre>
 * @author HuangFeng(2011-1-22)
 */
public class ParameterUtil {

	/**
	 * <pre>
	 * Api对象格式化
	 * -把对象转换成K,V对应表
	 * </pre>
	 * @author HuangFeng(2011-1-22)
	 * @param fmobj 待格式化对象
	 * @return K,V对应表
	 * @throws IllegalAccessException 非法访问出错
	 * @throws IllegalArgumentException 非法参数出错
	 */
	public static ApiParameter<String, Object> format(Object fmobj) throws IllegalArgumentException, IllegalAccessException
	{
		ApiParameter<String, Object> params = new ApiParameter<String, Object>();
		Class<?> classz = fmobj.getClass();
		for(Field field : classz.getDeclaredFields())
		{
			field.setAccessible(true);
			params.put(StringUtil.getBeforUpperCaseAddUnderline(field.getName()), field.get(fmobj));
		}
		
		return params;
	}
	
	/**
	 * <pre>
	 * Api对象格式化
	 * -把对象转换成K,V对应表
	 * </pre>
	 * @author HuangFeng(2011-1-22)
	 * @param fmobj 待格式化对象
	 * @return K,V对应表
	 * @throws IllegalAccessException 非法访问出错
	 * @throws IllegalArgumentException 非法参数出错
	 */
	public static ApiParameter<String, String> formatToStr(Object fmobj) throws IllegalArgumentException, IllegalAccessException
	{
		ApiParameter<String, String> params = new ApiParameter<String, String>();
		Class<?> classz = fmobj.getClass();
		Object value = null;
		for(Field field : classz.getDeclaredFields())
		{
			field.setAccessible(true);
			value = field.get(fmobj);
			if(Validator.isNull(value))
			{
				value = "";
			}
			
			params.put(StringUtil.getBeforUpperCaseAddUnderline(field.getName()), value.toString());
		}
		
		return params;
	}
	
	/**
	 * API参数表格式化成URL字符串<code>key=value&key1=value1&</code>
	 * @author HuangFeng(2011-1-22)
	 * @param params API参数表格
	 * @return URL字符串
	 */
	public static String format(ApiParameter<String, Object> params)
	{
		StringBuilder sb = new StringBuilder();
		for(String key : params.keySet())
		{
			sb.append(key).append("=").append(params.get(key)).append("&");
		}
		return sb.toString();
	}
}
